<template>
  <el-form ref="dataForm" label-position="left">
    <el-form-item v-for="config in configs" :label="config.title + ' ' + config.key">
      <el-input v-if="config.type == 1" v-model="config.value" :name="config.key" :placeholder="config.title" />
      <el-input v-else-if="config.type == 2" v-model="config.value" type="textarea" :name="config.key" :placeholder="config.title" />
      <el-radio-group v-else-if="config.type == 3" v-model="config.value">
        <el-radio v-for="option in formattingOptions(config.options)" :label="option.key" border>
          {{ option.label }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <div style="text-align:right;">
      <el-button type="primary" @click="saveConfig">保存</el-button>
    </div>
  </el-form>
</template>

<script>
import { getConfig, saveConfig } from '@/api/config'
import { Message } from 'element-ui'

export default {
  filters: {
  },
  props: {
    type: {
      type: String,
      default: 'base'
    }
  },
  data() {
    return {
      configs: [],
      loading: false,
      group: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formattingOptions(parameter) {
      const options = []
      parameter.split('|').map((config) => {
        config = config.split(':')
        options.push({ key: config[0], label: config[1] })
      })
      return options
    },
    getList() {
      this.loading = true
      this.$emit('create') // for test
      this.group = this.$route.query.tab ? this.$route.query.tab : 'base'
      getConfig({ group: this.group }).then(response => {
        this.configs = response.data
        this.loading = false
      })
    },
    saveConfig() {
      saveConfig(this.configs).then(response => {
        const { code } = response
        if (code === 1) {
          Message({
            message: '保存成功',
            type: 'success'
          })
        } else {
          Message({
            message: '保存失败',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

